package it.niedermann.android.markdown.markwon.handler

import android.text.Editable
import android.text.Spanned
import android.text.style.ClickableSpan
import android.view.View
import io.noties.markwon.base.core.spans.LinkSpan
import io.noties.markwon.base.editor.AbstractEditHandler
import io.noties.markwon.base.editor.PersistedSpans

class LinkEditHandler(private val onClick: OnClick) : AbstractEditHandler<LinkSpan>() {
    interface OnClick {
        fun onClick(widget: View, link: String)
    }

    override fun configurePersistedSpans(builder: PersistedSpans.Builder) {
        builder.persistSpan(EditLinkSpan::class.java, PersistedSpans.SpanFactory<EditLinkSpan> {
            EditLinkSpan(
                onClick
            )
        })
    }

    override fun handleMarkdownSpan(
        persistedSpans: PersistedSpans,
        editable: Editable,
        input: String,
        span: LinkSpan,
        spanStart: Int,
        spanTextLength: Int
    ) {
        val editLinkSpan = persistedSpans[EditLinkSpan::class.java]
        editLinkSpan.link = span.link
        val s: Int
        val e: Int

        // markdown link vs. autolink
        if ('[' == input[spanStart]) {
            s = spanStart + 1
            e = spanStart + 1 + spanTextLength
        } else {
            s = spanStart
            e = spanStart + spanTextLength
        }
        editable.setSpan(
            editLinkSpan,
            s,
            e,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
    }

    override fun markdownSpanType(): Class<LinkSpan> {
        return LinkSpan::class.java
    }

    internal class EditLinkSpan(private val onClick: OnClick) : ClickableSpan() {
        var link: String? = null
        override fun onClick(widget: View) {
            if (link != null) {
                onClick.onClick(widget, link!!)
            }
        }
    }
}